//
//  InprogressController.m
//  Runone
//
//  Created by ekkaLyn on 2017/3/13.
//  Copyright © 2017年 runone. All rights reserved.
//

#import "InprogressController.h"
#import "InProgressContentView.h"
#import "InProgressConstructPositionView.h"
#import "UnStartEventView.h"
#import "InProgressPicAndVideoView.h"
#import "PhotoesScrollView.h"
#import "YZInputView.h"
#import "EventDetailModel.h"
#import "SDAutoLayout.h"
#import "RequestHelper.h"
#import "EventDetailModel.h"
#import "MJExtension.h"
#import "SVProgressHUD.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "LittleVideoViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "BCNetAPIClient.h"
#import "AppDelegate.h"
#import "PileInfo.h"

@interface InprogressController ()<UIScrollViewDelegate, LittleVideoDelegate,AJPhotoPickerProtocol, AJPhotoBrowserDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate, UIAlertViewDelegate>{
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}
@property (nonatomic, strong) UIScrollView *scroollView;
@property (nonatomic, strong) UIView                          *wrapperView;
@property (nonatomic, strong) UIView                          *containerV;        // 容器
@property (nonatomic, strong) InProgressContentView           *constructV;        // 施工单位
@property (nonatomic, strong) InProgressContentView           *personInChargeV;   // 现场负责人
@property (nonatomic, strong) InProgressContentView           *contacterV;        // 联系人
@property (nonatomic, strong) InProgressContentView           *planBeginTimeV;    // 计划开始时间
@property (nonatomic, strong) InProgressContentView           *planEndTimeV;      // 计划结束时间
@property (nonatomic, strong) InProgressConstructPositionView *postionV;          //施工地点
@property (nonatomic, strong) InProgressConstructPositionView *beginPileNOV;      //开始桩号
@property (nonatomic, strong) InProgressConstructPositionView *endPileNOV;        //结束桩号
@property (nonatomic, strong) InProgressContentView           *vehicleDirectionV; //行车方向
@property (nonatomic, strong) InProgressContentView           *constructProjectV; //施工项目
@property (nonatomic, strong) UnStartEventView                *constructDesV;     //施工描述
@property (nonatomic, strong) PhotoesScrollView               *photoesV;          //选中的图片的view
@property (nonatomic, strong) InProgressPicAndVideoView       *picAndVideoV;      // 图片和视频按钮
//@property (nonatomic, strong) UIView                          *lastBottomLine;
@property (nonatomic, strong) UIScrollView                    *imageScrollV;      //图片
@property (nonatomic, strong) UIView                          *videoView;         //小视频
@property (nonatomic, strong) NSURL                           *videoUrl;
@property (nonatomic, strong) EventDetailModel                *Model; //请求返回的事件模型
@property (nonatomic, strong) NSMutableArray                  *selectPhoteArray; //选中的图片数组
@end

@implementation InprogressController
#pragma mark - lazy load
- (UIScrollView *)scroollView {
    if (!_scroollView) {
        _scroollView = [UIScrollView new];
        _scroollView.delegate = self;
        _scroollView.bounces  = NO;
        [self.view addSubview:_scroollView];
        _scroollView.showsVerticalScrollIndicator = YES;
        _scroollView.showsHorizontalScrollIndicator = NO;
        _scroollView.sd_layout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.view, 0);
    }
    return _scroollView;
}
- (PhotoesScrollView *)photoesV {
    if (!_photoesV) {
        PhotoesScrollView *photoesV = [[PhotoesScrollView alloc] init];
        _photoesV = photoesV;
        [self.containerV addSubview:_photoesV];
        self.photoesV.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 16)
        .heightIs(100)
        .topSpaceToView(self.constructDesV, 10)
        .centerXEqualToView(self.containerV)
        ;
    }
    return _photoesV;
}
- (UIView *)videoView {
    if (!_videoView) {
        UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 20, 200)];
        _videoView = newView;
        newView.backgroundColor = [UIColor yellowColor];
        [self.containerV addSubview:_videoView];
        
    }
    return _videoView;
}

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.view.backgroundColor = [UIColor redColor];
//     self.automaticallyAdjustsScrollViewInsets = NO;
    [self configUI];
    [self configNaviABar];
    [self setUpArray] ;
    [self requestData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
#pragma mark -  navagationBar
- (void) configNaviABar {
    UIButton *commitBtn = [[UIButton alloc] init];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [commitBtn setBackgroundImage:[UIImage imageNamed:@"event_check_commit"] forState:UIControlStateNormal];
    commitBtn.frame         = CGRectMake(0, 0, 40, 20);
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *commit = [[UIBarButtonItem alloc] initWithCustomView:commitBtn];
    
    UIButton *cancleBtn = [[UIButton alloc] init];
    [cancleBtn setTitle:@"结束" forState:UIControlStateNormal];
    cancleBtn.frame         = CGRectMake(0, 0, 40, 20);
    [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancle = [[UIBarButtonItem alloc] initWithCustomView:cancleBtn];
    
    self.navigationItem.rightBarButtonItems = @[commit, cancle];
    //主标题
    UILabel *titleL               = [[UILabel alloc] init];
    titleL.text                   = @"进行中事件";
    titleL.frame                  = CGRectMake(0, 0, 150, 30);
    titleL.textAlignment          = NSTextAlignmentCenter;
    titleL.textColor              = [UIColor whiteColor];
    self.navigationItem.titleView = titleL;
}
#pragma mark - UI
- (void) configUI {
    self.view.backgroundColor = [UIColor colorWithRed:226.0 / 255 green:230.0 / 255 blue:240.0 / 255 alpha:1];
    self.wrapperView = [UIView new];
    self.wrapperView.backgroundColor = [UIColor colorWithRed:239.0 / 255 green:239.0 / 255 blue:249.0 / 255 alpha:0.8];
    [self.scroollView addSubview:self.wrapperView];
    [self configContainerV];
    [self configConstructV];
    [self configPersonInCharge];
    [self configContacterV];
    [self configPlanBeginTimeV];
    [self configPlanEndTimeV];
    [self configConstructPositionV];
    [self configBeginPileNOV];
    [self configEndPileNOV];
    [self configConstructDirectionV];
    [self configConstructProjectV];
    [self configConstructDescriptionV];
    [self configPicAndVideoView];
    self.wrapperView.sd_layout
    .leftEqualToView(self.scroollView)
    .rightEqualToView(self.scroollView)
    .topEqualToView(self.scroollView)
    ;
    [self.containerV setupAutoHeightWithBottomView:self.constructDesV bottomMargin:10]   ;
    [self.wrapperView setupAutoHeightWithBottomView:self.picAndVideoV bottomMargin:10]   ;
    [self.scroollView setupAutoContentSizeWithBottomView:self.wrapperView bottomMargin:0];

}

- (void) configContainerV {
    self.containerV = [[UIView alloc] init];
    [self.wrapperView addSubview:self.containerV];
    self.containerV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.wrapperView, 0)
    .autoHeightRatio(0)
    ;
}

- (void) configConstructV {
    self.constructV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"施 工 单 位:"];
    [self.containerV addSubview:self.constructV];
    self.constructV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
-(void) configPersonInCharge {
    self.personInChargeV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"现 场 负 责 人:"];
    [self.containerV addSubview:self.personInChargeV];
    self.personInChargeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.constructV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configContacterV {
    self.contacterV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"联  系  人:"] ;
    [self.containerV addSubview:self.contacterV];
    self.contacterV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.personInChargeV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configPlanBeginTimeV {
    self.planBeginTimeV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"计划开始时间:"];
    [self.containerV addSubview:self.planBeginTimeV];
    self.planBeginTimeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.contacterV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configPlanEndTimeV {
    self.planEndTimeV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"计划结束时间:"];
    [self.containerV addSubview:self.planEndTimeV];
    self.planEndTimeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.planBeginTimeV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructPositionV {
    self.postionV = [[InProgressConstructPositionView alloc] initWithDefalutHeight:50.0 title:@"施 工 地 点:" isCanTouch:NO];
    [self.containerV addSubview:self.postionV];
    self.postionV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.planEndTimeV,0)
    .autoHeightRatio(0)
    ;
}
- (void)configBeginPileNOV {
   self.beginPileNOV =[[InProgressConstructPositionView alloc] initWithDefalutHeight:50.0 title:@"开 始 桩 号:" isCanTouch:NO];
    [self.containerV addSubview:self.beginPileNOV];
    self.beginPileNOV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.postionV,0)
    .autoHeightRatio(0)
    ;

}
- (void)configEndPileNOV {
    self.endPileNOV =[[InProgressConstructPositionView alloc] initWithDefalutHeight:50.0 title:@"结 束 桩 号:" isCanTouch:NO];
    [self.containerV addSubview:self.endPileNOV];
    self.endPileNOV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.beginPileNOV,0)
    .autoHeightRatio(0)
    ;
}

- (void) configConstructDirectionV {
    self.vehicleDirectionV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"行 车 方 向:"];
    [self.containerV addSubview:self.vehicleDirectionV];
    self.vehicleDirectionV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.endPileNOV,0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructProjectV {
    self.constructProjectV = [[InProgressContentView alloc] initWithDefalutHeight:50.0 title:@"施 工 项 目:"];
    [self.containerV addSubview:self.constructProjectV];
    self.constructProjectV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.vehicleDirectionV,0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructDescriptionV {
    self.constructDesV = [[UnStartEventView alloc] initWithDefalutHeight:50.0 title:@"施 工 描 述:" ];
    [self.containerV addSubview:self.constructDesV];
    self.constructDesV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.constructProjectV,0)
    .autoHeightRatio(0)
    ;
}

- (void) configPicAndVideoView {
    self.picAndVideoV = [[InProgressPicAndVideoView alloc] initWithDefalutHeight:40.0];
    [self.wrapperView addSubview:self.picAndVideoV];
    [self.picAndVideoV.picturesBtn addTarget:self action:@selector(photoesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.picAndVideoV.videoBtn addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.picAndVideoV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.containerV, 10)
    .autoHeightRatio(0)
    ;
}

#pragma mark - 导航栏按钮点击
- (void) commitBtnClick {
    if (self.constructDesV.desTextV.text.length == 0)  {
        [SVProgressHUD showErrorWithStatus:@"施工处置不能为空"];
        return;
    }
    [self postDataToServer];
}

- (void) postDataToServer {
    [SVProgressHUD showWithStatus:@"正在上报中..."];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL         = GetEventDataURL;
    getCurrentEventModel.DataValue   = [self dataValueString];
    getCurrentEventModel.UpdatedTime = @"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode  = @"GuangleHighway";
    getCurrentEventModel.MethodName  = @"AddConstructionEventDeal";
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":getCurrentEventModel.MethodName,@"updatedtime":getCurrentEventModel.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":getCurrentEventModel.DataValue};
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:_selectPhoteArray videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        //[SVProgressHUD showSuccessWithStatus:@"成功"];
        [SVProgressHUD dismiss];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (NSString *)dataValueString {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"IncidentUID\",\"value\":\"%@\"},{\"key\":\"DealDetail\",\"value\":\"%@\"}]",_reportModel.IncidentUID,self.constructDesV.desTextV.text];
    return valueStr;
}

- (void) cancleBtnClick {
    UIAlertView *showAlert=[[UIAlertView alloc] initWithTitle:nil message:@"是否确认结束该事件" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [showAlert show];
}
#pragma mark - AlertViewDelegate  (点击结束按钮)
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
    }
    if (buttonIndex == 1) {
        if ([self.constructDesV.desTextV.text length] == 0) {
            [SVProgressHUD showErrorWithStatus:@"请在施工处置说明为何结束此事件"];
            return;
        }
        
        RequestGinsengModel *CancleConstructionEventDetailInfoModel =[[RequestGinsengModel alloc] init];
        CancleConstructionEventDetailInfoModel.URL         = GetEventDataURL;
        CancleConstructionEventDetailInfoModel.MethodName  = @"StopOrCancelConstructionEvent";
        CancleConstructionEventDetailInfoModel.DataValue   = [self dataValueString];
        CancleConstructionEventDetailInfoModel.UpdatedTime = @"";
        CancleConstructionEventDetailInfoModel.SystemCode  = @"GuangleHighway";
        
        [self endTheEvent];
    }
}
#pragma mark - 提交结束事件
- (void) endTheEvent {
    [SVProgressHUD showWithStatus:@"正在上传,请稍后......"];
    RequestGinsengModel *CancleConstructionEventDetailInfoModel =[[RequestGinsengModel alloc] init];
    CancleConstructionEventDetailInfoModel.URL         = GetEventDataURL;
    CancleConstructionEventDetailInfoModel.MethodName  = @"StopOrCancelConstructionEvent";
    CancleConstructionEventDetailInfoModel.DataValue   = [self dataValueString];
    CancleConstructionEventDetailInfoModel.UpdatedTime = @"";
    CancleConstructionEventDetailInfoModel.SystemCode  = @"GuangleHighway";
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":CancleConstructionEventDetailInfoModel.MethodName,@"updatedtime":CancleConstructionEventDetailInfoModel.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":CancleConstructionEventDetailInfoModel.DataValue};
    
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:self.selectPhoteArray videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        [SVProgressHUD dismiss];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

#pragma mark -  图片和视频按钮点击
- (void) videoBtnClick {
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void) photoesBtnClick {
    if (self.selectPhoteArray.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5 - self.selectPhoteArray.count;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark- init
- (void) setUpArray {
    _selectPhoteArray = [[NSMutableArray alloc] init];
}

#pragma mark - request
- (void) requestData {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetConstructionEventDetailInfo = [[RequestGinsengModel alloc] init];
    GetConstructionEventDetailInfo.URL         = GetEventDataURL;
    GetConstructionEventDetailInfo.DataValue   = [self getConstructDataValueStr:self.reportModel.IncidentUID];
    GetConstructionEventDetailInfo.UpdatedTime = @"";
    GetConstructionEventDetailInfo.SystemCode  = @"GuangleHighway";
    GetConstructionEventDetailInfo.MethodName  = @"GetConstructionEventDetailInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        _Model = [EventDetailModel mj_objectWithKeyValues:requestOutginseng.DataValue];
        [self refreshUIData]; //刷新UI数据
    };
    [requestHelper RequestGinsengModel:GetConstructionEventDetailInfo andPushController:self];
}
-(NSString *)getConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EventUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}

#pragma mark - 刷新数据
- (void) refreshUIData {
    [self.constructV setContentString:_Model.Department] ;
    [self.personInChargeV setContentString:_Model.Header];
    [self.contacterV setContentString:_Model.Telephone]  ;
    [self.planBeginTimeV setContentString:_Model.EventBaseInfo.OccurTime];
    [self.planEndTimeV setContentString:_Model.EventBaseInfo.EndTime];
    [self.vehicleDirectionV setContentString:_Model.EventBaseInfo.RoadDerectionName];
    
    if (_Model.EventBaseInfo.TollStationName.length > 0) {
        [self.postionV setMiddelString:@"收费站" rightString:_Model.EventBaseInfo.TollStationName];
    }else {
        NSString *isRampStr = _Model.EventBaseInfo.IsRamp ? @"非主线" : @"主线";
        
        [self.postionV setMiddelString:_Model.EventBaseInfo.RoadName rightString:isRampStr];
    }
    // 桩号
    NSString *b                 = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.BeginPile];
    NSString *begin             = [b stringByReplacingOccurrencesOfString:@"K" withString:@" "];
    NSString *beginDistance     = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.BeginPileDistance];
    NSString *bd                = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.EndPile];
    NSString *end               = [bd stringByReplacingOccurrencesOfString:@"K" withString:@" "];
    NSString *endDistance       = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.EndPileDistance];
    if ([_Model.EventBaseInfo.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        NSString *kBeginStr = [NSString stringWithFormat:@"K %@",begin];
        [self.beginPileNOV setMiddelString:kBeginStr rightString:beginDistance];
        
        NSString *kEndStr = [NSString stringWithFormat:@"K %@",end];
        [self.endPileNOV setMiddelString:kEndStr rightString:endDistance];
        
    } else {
        NSString *lkBeginStr = [NSString stringWithFormat:@"LK %@",begin];
        [self.beginPileNOV setMiddelString:lkBeginStr rightString:beginDistance];
        
        NSString *lkEndStr = [NSString stringWithFormat:@"LK %@",end];
        [self.endPileNOV setMiddelString:lkEndStr rightString:endDistance];
    }
    
    [self.constructProjectV setContentString:_Model.Content];

}
#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    if ((self.selectPhoteArray.count + assets.count) > 5)  {
        [SVProgressHUD showSuccessWithStatus:@"不能超过5张"];
        return;
    }
    [picker dismissViewControllerAnimated:NO completion:nil];
    for (int i = 0; i < assets.count; i ++) {
        ALAsset *asset =  assets[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [self.selectPhoteArray addObject:tempImg];
    }
    [self reConfigPhotoesView];
}

- (void) reConfigPhotoesView {
    for (UIImageView *imgV in self.photoesV.scrollV.subviews) {
        [imgV removeFromSuperview];
    }
    CGFloat x = 5;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    
    self.photoesV.scrollV.contentSize = CGSizeMake(105 * self.selectPhoteArray.count + 5, 0);
    for (int i = 0 ; i < self.selectPhoteArray.count; i++) {
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds          = YES;
        imageView.image                  = self.selectPhoteArray[i];
        imageView.tag                    = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [self.photoesV.scrollV addSubview:imageView];
        
        x += frame.size.width+5;
    }
    [self.containerV setupAutoHeightWithBottomView:self.photoesV bottomMargin:10];
    [self.containerV layoutSubviews];
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.selectPhoteArray index:index];
    photoBrowserViewController.delegate = self;
    //    UIImage *img = self.selectPhoteArray[index];
    [self.selectPhoteArray removeObjectAtIndex:index];
    
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
    
}
- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
    [self reConfigPhotoesView];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        //        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        //        NSLog(@"保存到相册出错%@", error);
    }
}
// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    UIView *view;
    if (self.selectPhoteArray.count > 0) {
        view = self.photoesV;
    }else {
        view = self.constructDesV;
    }
    
    if (_videoUrl) {
        self.videoView.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 20)
        .heightEqualToWidth(0)
        .topSpaceToView(view, 10)
        .centerXEqualToView(self.containerV)
        ;
        [self.containerV setupAutoHeightWithBottomView:self.videoView bottomMargin:10];
        [self.containerV layoutSubviews];
    }

    [self crreatPlayViedeo:filePath];
    
}
- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.videoView.layer addSublayer:_playerLayer];
    [_player play];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
}

@end
